package com.yywq.controller;

import com.yywq.pojo.model.GoodsInfo;
import com.yywq.pojo.model.UserToken;
import com.yywq.response.CommonReturnType;
import com.yywq.service.impl.GoodsServiceImpl;
import com.yywq.service.impl.OrdersServiceImpl;
import com.yywq.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * @author 29216
 * @author: 吴磊
 * @program: yywq_parent
 * @create: 2021-04-16 18:57
 */
@RestController
@RequestMapping("/deal")
/**
 * 此模块必须要登录
 */
public class TradingController {

    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private GoodsServiceImpl goodsService;
    @Autowired
    private OrdersServiceImpl ordersService;

    /**
     * @param gid       商品ID
     * @param addressId 商品地址ID
     * @param sid       卖家ID
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/buy", method = RequestMethod.POST)
    private CommonReturnType buyGood(@RequestParam("gid") String gid,
                                     @RequestParam("addressId") String addressId,
                                     @RequestParam("sid") String sid) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String token = request.getHeader("Authorization");
        //通过Token获取买家信息
        UserToken userToken = tokenUtils.getInfoFromToken(token);
        String bid = userToken.getId();
//        String bid = "d86c0813w35eew4210wa099w6c95f686cc10";
        GoodsInfo goodsInfo = goodsService.getGoodsInfo(gid);
        BigDecimal price = goodsInfo.getDisPrice();
        ordersService.generateOrders(bid, sid, addressId, gid, price);
        return CommonReturnType.create(null);
    }
}
